package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/gin-gonic/gin"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_apply/repository"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_apply/service"
	"github.com/spf13/viper"
)

func main() {

	configFilePath := flag.String("config", "../../conf", "Path to the configuration file")
	flag.Parse()

	InitConfig(*configFilePath)

	db := repository.InitDB()
	defer db.Close()

	r := CollectRoute(gin.Default())
	port := viper.GetString("listen_port")
	if port != "" {
		panic(r.Run(":" + port))
	}
	panic(r.Run()) // listen and serve on 0.0.0.0:8080

}

func CollectRoute(r *gin.Engine) *gin.Engine {

	v1 := r.Group("/v1")
	{
		v1.POST("/apply/new/file", service.PostNewFile) // 接收监控新增文件
		v1.POST("/apply/new/data", service.PostNewJsonData)

		v1.POST("/apply/replace/file", service.PostReplaceFile) // 接收监控替换的文件
		v1.POST("/apply/replace/data", service.PostReplaceJsonData)

		v1.POST("/apply/delete/file", service.PostDeleteFile) // 接收监控删除的文件
		v1.POST("/apply/delete/data", service.PostDeleteJsonData)
	}
	return r
}

func InitConfig(path string) {

	// viper库初始化
	viper.SetConfigName("monitor_apply")
	viper.SetConfigType("yml")
	viper.AddConfigPath(path)
	err := viper.ReadInConfig()
	if err != nil {
		panic("")
	}

	// log库初始化
	file := viper.GetString("log_path") + "/message.log"
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
	if err != nil {
		fmt.Println("errrrrrrrr")
		return
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
